package com.example.cloud.service.system.impl;

import com.example.cloud.dao.mongdb.system.MongoDepartmentRepository;
import com.example.cloud.dao.system.DepartmentRepository;
import com.example.cloud.model.system.Department;
import com.example.cloud.model.system.User;
import com.example.cloud.service.system.DepartmentService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by wangtao on 2018/2/3.
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    private static final Logger logger = Logger.getLogger(DepartmentServiceImpl.class);

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private MongoDepartmentRepository mongoDepartmentRepository;

    @Override
    public Department findOneFromCache(Long id) {
        return mongoDepartmentRepository.findOne(id);
    }

    @Override
    public List<Department> findAllFromCache() {
        return mongoDepartmentRepository.findByAccountIdAndDeleteFlag(RequestUtil.getLoginUser().getAccountId(),0);
    }

    @Override
    @Transactional
    public void doSave(Department record) {
        if(record.getId() == null){
            User user = RequestUtil.getLoginUser();
            record.setAccountId(user.getAccountId());
            record.setOrganId(user.getOrganId());
            record.setOrganName(user.getOrganName());
        }
        BusinessUtil.appendRecord(record);
        departmentRepository.save(record);
        // 同步缓存
        mongoDepartmentRepository.save(record);
    }

    @Override
    public void loadCache() {
        List<Department> list = departmentRepository.findAll();
        if(!list.isEmpty()){
            mongoDepartmentRepository.save(list);
            logger.info("*******************部门已全部同步缓存*******************");
        }
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        // 删除数据库
        departmentRepository.deleteByIdIn(ids);
        // 删除缓存
        mongoDepartmentRepository.deleteByIdIn(ids);
    }
}
